package jBittorrentAPI.strategy;

import jBittorrentAPI.DownloadManager;

import java.util.ArrayList;

public class SlidingWindowAlgoritme implements PiecePickingStrategy {

	public DownloadManager dm;
	PiecePickingStrategy pps;
	int n = -1;
	int initHighPioritySet = 20;
	ArrayList<Integer> highPioritySet = new ArrayList<Integer>();
	
	public SlidingWindowAlgoritme(DownloadManager dm){
		this.dm = dm;
	}
	@Override
	public int choosingAlgoritme(ArrayList<Integer> possible) {
		this.pps = new RarestFirstAlgoritme(dm);
		return chooseSlidingWindowAlgoritme();
	}
	
	@Override
	public synchronized void removeIndex(int i) {
		highPioritySet.remove(new Integer(i));
	}

	private synchronized int chooseSlidingWindowAlgoritme(){
		if(highPioritySet.size() < initHighPioritySet && !dm.isComplete()){
			n = dm.isComplete.nextClearBit(n+1);
			if(n < dm.getNumberOfPieces()) highPioritySet.add(n);
			int m = -1;
			while(highPioritySet.size() < initHighPioritySet){
				m = dm.isComplete.nextClearBit(n+1);
				if(m >= dm.getNumberOfPieces()) break;
				highPioritySet.add(m);
				n = m;
			}
		}

		if(highPioritySet.size() > 0){
			int m = pps.choosingAlgoritme(highPioritySet);
			dm.setRequested(m, true);
			return m;
		}else{
			return -1;
		}
	}
}
